package com.ziq.base.manager

import android.text.TextUtils
import com.google.gson.GsonBuilder
import com.ziq.base.base.hilt.GlobalConfigModule
import com.ziq.base.utils.LogUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class RetrofitManager @Inject constructor() {

    @Inject
    lateinit var globalConfigModule: GlobalConfigModule

    private val mRetrofitMap = HashMap<String, Retrofit>()

    fun getRetrofit(baseUrl: String): Retrofit? {
        // 初始化okhttp
        return if (!TextUtils.isEmpty(baseUrl)) {
            if (mRetrofitMap.containsKey(baseUrl)) {
                mRetrofitMap.get(baseUrl)
            } else {
                val loggerInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
                    override fun log(message: String) {
                        LogUtil.i("OkHttp:", message)
                    }
                }) //打印 信息
                loggerInterceptor.apply {
                    loggerInterceptor.level = HttpLoggingInterceptor.Level.BODY
                }
                val builder = OkHttpClient.Builder().addNetworkInterceptor(loggerInterceptor)

                if(!globalConfigModule.isNetworkVerify){
                    builder.sslSocketFactory(
                        SSLFactory.sslContext.socketFactory,
                        SSLFactory.xtm
                    ).hostnameVerifier(SSLFactory.DO_NOT_VERIFY)
                }

                for (config in globalConfigModule.configModules){
                    config.setupOkHttpClient(builder)
                }

                val client: OkHttpClient = builder.build()
                // 初始化Retrofit
                val tempRetrofit = Retrofit.Builder()
                    .client(client)
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
                mRetrofitMap[baseUrl] = tempRetrofit
                tempRetrofit
            }
        } else {
            throw RuntimeException("Retrofit 初始化 baseUrl 不能为空")
        }
    }
}